import 'dart:io';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:image_pickers/image_pickers.dart';
import 'package:xvideos/hj_page/darkweb/widget/add_media_source_button.dart';
import 'package:xvideos/hj_utils/permission_util.dart';

class PhotoManageView extends StatefulWidget {
  final Function(List<String> resources)? resourceOnchanged;
  final int max;
  const PhotoManageView({super.key, this.resourceOnchanged, this.max = 9});

  @override
  State<PhotoManageView> createState() => _PhotoManageViewState();
}

class _PhotoManageViewState extends State<PhotoManageView> {
  final dataSource = <String>[];
  @override
  Widget build(BuildContext context) {
    return GridView.builder(
      shrinkWrap: true,
      physics: NeverScrollableScrollPhysics(),
      gridDelegate:
          const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3, mainAxisSpacing: 8, crossAxisSpacing: 8, childAspectRatio: 1),
      itemCount: min(dataSource.length + 1, 9),
      itemBuilder: (BuildContext context, int index) {
        if (index == dataSource.length)
          return AddMediaSourceButton(
            isVideo: false,
            onTap: _addAlbumPhotos,
            backgroundColor: Colors.black.withOpacity(.04),
          );
        return ClipRRect(
          borderRadius: BorderRadius.circular(8),
          child: Stack(
            children: [
              Image.file(
                File(dataSource[index]),
                width: double.infinity,
                height: double.infinity,
                fit: BoxFit.cover,
              ),
              Positioned(
                  right: 6,
                  top: 6,
                  child: GestureDetector(
                    onTap: () {
                      dataSource.removeAt(index);
                      setState(() {});
                    },
                    child: Container(
                      width: 20,
                      height: 20,
                      decoration: BoxDecoration(color: Colors.white.withOpacity(.8), borderRadius: BorderRadius.circular(10)),
                      alignment: Alignment.center,
                      child: const Icon(
                        Icons.close,
                        size: 14,
                      ),
                    ),
                  ))
            ],
          ),
        );
      },
    );
  }

  _addAlbumPhotos() async {
    if (await PermissionUtil.checkPhotoPermission()) {
      final listMedia = await ImagePickers.pickerPaths(
        uiConfig: UIConfig(uiThemeColor: Colors.white),
        galleryMode: GalleryMode.image,
        selectCount: 9 - dataSource.length,
        showCamera: false,
      );
      if (listMedia.isEmpty) return;
      final ret = listMedia.map((e) => e.path ?? '').toList();
      dataSource.addAll(ret);
      setState(() {});
      widget.resourceOnchanged?.call(dataSource);
    }
  }
}
